class Solution {
public:
    using PII=pair<int, int>;
    int minOperations(vector<int>& nums) {
        int n=nums.size(), gcd_all=0, cnt1=0;
        for(int x:nums) gcd_all=gcd(gcd_all, x), cnt1+=x==1;
        if(gcd_all>1) return -1;
        if(cnt1) return n-cnt1;

        int min_size=n;
        vector<PII> g; //<GCD, 相同GCD的右端点>
        for(int i=0; i<n; i++) {
            g.emplace_back(nums[i], i); //原地去重
            int j=0;
            for(auto &p:g) {
                p.first=gcd(p.first, nums[i]);
                if(g[j].first==p.first) g[j].second=p.second;
                else g[++j]=move(p);
            }
            g.resize(j+1);
            if(g[0].first==1) 
                min_size=min(min_size, i-g[0].second);
        }
        return min_size+n-1;
    }
};